<template>
  <el-card class="page-card">
    <h2>促销活动列表</h2>
    <!-- 搜索栏 -->
    <el-form :inline="true" :model="query" class="filter-form" @submit.prevent>
      <el-form-item label="名称">
        <el-input v-model="query.name" placeholder="活动名称关键词" clearable />
      </el-form-item>
      <el-form-item label="类型">
        <el-select v-model="query.type" placeholder="全部" clearable style="width: 160px">
          <el-option v-for="(label,val) in typeMap" :key="val" :label="label" :value="val" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchList()">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="toolbar">
      <el-button type="primary" @click="openCreate">新增活动</el-button>
    </div>

    <!-- 表格 -->
    <div class="table-container">
      <el-table :data="list" border stripe height="520px">
        <el-table-column type="index" width="60" label="#" />
        <el-table-column prop="id" label="ID" width="90" />
        <el-table-column prop="name" label="活动名称" show-overflow-tooltip />
        <el-table-column prop="type" label="类型" width="120">
          <template #default="{ row }">{{ typeMap[row.type] || row.type }}</template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="210" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="openEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        v-model:page-size="pageSize"
        v-model:current-page="pageNum"
        :page-sizes="[10,20,50,100]"
        @current-change="fetchList"
        @size-change="fetchList"
      />
    </div>

    <!-- 新增/编辑 弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.isEdit ? '编辑活动' : '新增活动'" width="480px" destroy-on-close>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="form.name" maxlength="100" show-word-limit />
        </el-form-item>

        <el-form-item label="类型" prop="type" v-if="!dialog.isEdit">
          <el-select v-model="form.type" placeholder="请选择活动类型" style="width: 220px">
            <el-option v-for="(label,val) in typeMap" :key="val" :label="label" :value="val" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" v-else>
          <el-tag type="info">{{ typeMap[form.type] }}</el-tag>
        </el-form-item>

        <el-form-item label="时间范围" required>
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getPromotionList,
  createPromotion,
  updatePromotion,
  deletePromotion
} from '@/api/admin'
import dayjs from 'dayjs'

const typeMap = {
  1: '秒杀',
  2: '团购',
  3: '满减',
  4: '套餐'
}

// 查询参数 & 分页
const query = reactive({ name: '', type: null })
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const list = ref([])

const fetchList = async () => {
  try {
    const res = await getPromotionList(pageNum.value, pageSize.value, query)
    const data = res.data.data // PageDTO
    list.value = data.list
    total.value = data.list.length
  } catch (e) {
    ElMessage.error('加载失败')
  }
}

const resetQuery = () => {
  query.name = ''
  query.type = null
  pageNum.value = 1
  fetchList()
}

// 弹窗 & 表单
const dialog = reactive({
  visible: false,
  isEdit: false
})
const form = reactive({
  id: null,
  name: '',
  type: null,
  startTime: '',
  endTime: ''
})
const dateRange = ref([])
const formRef = ref(null)

const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }]
}

const openCreate = () => {
  dialog.isEdit = false
  dialog.visible = true
  Object.assign(form, { id: null, name: '', type: null, startTime: '', endTime: '' })
  dateRange.value = null
}

const openEdit = (row) => {
  dialog.isEdit = true
  dialog.visible = true
  Object.assign(form, row)
  dateRange.value = [new Date(row.startTime), new Date(row.endTime)]
}

const submitForm = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return
    if (!dateRange.value || dateRange.value.length !== 2) {
      ElMessage.warning('请选择开始和结束时间')
      return
    }
    form.startTime = dayjs(dateRange.value[0]).format('YYYY-MM-DD HH:mm:ss')
    form.endTime   = dayjs(dateRange.value[1]).format('YYYY-MM-DD HH:mm:ss')

    try {
      if (dialog.isEdit) {
        await updatePromotion({
          id: form.id,
          name: form.name,
          startTime: form.startTime,
          endTime: form.endTime
        })
        ElMessage.success('编辑成功')
      } else {
        await createPromotion({
          name: form.name,
          type: form.type,
          startTime: form.startTime,
          endTime: form.endTime
        })
        ElMessage.success('新增成功')
      }
      dialog.visible = false
      fetchList()
    } catch (e) {
      ElMessage.error(e.response?.data?.message || '操作失败')
    }
  })
}

const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除【${row.name}】吗？删除将同时清理相关子表数据！`, '提示', {
    type: 'warning'
  }).then(async () => {
    await deletePromotion(row.id)
    ElMessage.success('删除成功')
    if (list.value.length === 1 && pageNum.value > 1) {
      pageNum.value--
    }
    fetchList()
  })
}

onMounted(fetchList)
</script>

<style scoped>
.page-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.filter-form {
  margin-bottom: 20px;
}
.toolbar {
  margin-bottom: 20px;
}
.table-container {
  flex: 1;
  overflow: auto;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
